package com.ch.mobilesha.img;

import java.io.File;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.ch.mobilesha.R;

public class RemoteImageView extends ImageView {
	private String mLocal;
	private String mRemote;
	private HTTPThread mThread = null;
	private int defaultImageResourceId;
	private boolean isRoundedCorner;

	public RemoteImageView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public RemoteImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public RemoteImageView(Context context) {
		super(context);
	}

	public void setLocalURI(String local) {
		mLocal = local;
	}

	public void setRemoteURI(String uri) {
		if (uri != null && uri.startsWith("http")) {
			mRemote = uri;
		}
	}

	public void setDefaultImageResourceId(int defaultImageResourceId) {
		this.defaultImageResourceId = defaultImageResourceId;
	}

	public void setRoundedCorner(boolean isRoundedCorner) {
		this.isRoundedCorner = isRoundedCorner;
	}


	public void loadImage() {
		if (mRemote != null) {
			if (mLocal == null) {
				mLocal=FileManager.getImgFolderPath()+ "/"+ mRemote.hashCode();
			}
			File local = new File(mLocal);
			if (local.exists()) {
				setFromLocal();
			} else {
				local.getParentFile().mkdirs();
				queue();
			}
		}
	}

	@Override
	public void finalize() {
		if (mThread != null) {
			HTTPQueue queue = HTTPQueue.getInstance();
			queue.dequeue(mThread);
		}
	}

	private void queue() {
		if (mThread == null) {
			mThread = new HTTPThread(mRemote, mLocal, mHandler);
			HTTPQueue queue = HTTPQueue.getInstance();
			queue.enqueue(mThread, HTTPQueue.PRIORITY_HIGH);
		}
		if (defaultImageResourceId != 0) {
			setImageResource(defaultImageResourceId);
		} else {
			setImageResource(R.drawable.a_image_loding);
		}
	}

	Bitmap bitmap = null;

	private void setFromLocal() {

		mThread = null;
		BitmapFactory.Options bfo = new BitmapFactory.Options();
		bfo.inJustDecodeBounds = true;
		bitmap = BitmapFactory.decodeFile(mLocal);
		// Drawable d = Drawable.createFromPath(mLocal);
		if (bitmap != null) {
			if (isRoundedCorner) {
				bitmap = ImageUtil.getRoundedCornerBitmap(bitmap, 6);
				setImageBitmap(bitmap);
			} else {
				setImageBitmap(bitmap);
			}
		}
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			setFromLocal();
		}
	};
}
